package com.cfc.stage1;

import org.junit.Test;

/**
 * @description: 买卖股票的最佳时机
 *   https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/description/
 * @author: yangxuan10
 * @create: 2024-04-24 11:33
 **/
public class MaxProfit {

    @Test
    public void test1() {

        System.out.println(maxProfit1(new int[]{7,3,10,3,1,6}));
    }

    public int maxProfit1(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice) {
                minprice = prices[i];
            } else if (prices[i] - minprice > maxprofit) {
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }

    public int maxProfit(int[] prices) {
        int maxProfic = 0;
        int mairuValue = 0;
        int maichuValue = 0;
        int temp;
        for (int i = 0;i < prices.length-1; i++) {
            if (maxProfic > 0 && (prices[i] > mairuValue || prices[i] == maichuValue)) {
                continue;
            }
            for (int j = i+1;j < prices.length; j++) {
                temp =  prices[j] - prices[i];
                if (temp <= 0) {
                    break;
                }
                if (temp > maxProfic) {
                    maxProfic = temp;
                    mairuValue = prices[i];
                    maichuValue = prices[j];
                }
            }
        }
        return maxProfic;
    }

}